package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;

    // 用户下单
    @Override
    public void submit(Order order) {
        // 1.获取登录人user对象
        User user = UserHolder.get();
        if (user == null) {
            throw new CustomException("登录人为空不能下单");
        }
        // 2.根据id查询收货地址
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new CustomException("收货地址为空不能下单");
        }
        // 3.获取购物车列表
        List<Cart> cartList = cartService.list();
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException("购物车为空不能下单");
        }

        //通过mapper生成id
        long orderId = IdWorker.getId();

        //订单金额
        BigDecimal amount = new BigDecimal(0);

        //遍历购物车
        for (Cart cart : cartList) {
            //封装订单明细
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());//套餐或菜品名称
            orderDetail.setOrderId(orderId);//订单id
            orderDetail.setDishId(cart.getDishId());//菜品id
            orderDetail.setSetmealId(cart.getSetmealId());//套餐id
            orderDetail.setDishFlavor(cart.getDishFlavor());//口味
            orderDetail.setNumber(cart.getNumber());//数量
            orderDetail.setAmount(cart.getAmount());//金额
            orderDetail.setImage(cart.getImage());//图片
            //mapper保存
            orderDetailMapper.insert(orderDetail);

            //累加
            // amount=amount+(cart.getAmount()*cart.getNumber());
            amount = amount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));

            //订单
            order.setId(orderId);//订单号
            order.setNumber(String.valueOf(orderId));//订单状态
            order.setStatus(1);//待付款
            order.setUserId(user.getId());//下单用户
            order.setOrderTime(new Date());//下单时间
            order.setAmount(amount);//实收金额
            order.setUserName(user.getName());//下单用户名称
            order.setPhone(address.getPhone());//收获人手机号
            order.setAddress(address.getDetail());//收获人地址
            order.setConsignee(address.getConsignee());//收货人名称
            order.setCheckoutTime(new Date());//结账时间

            //mapper保存
            orderMapper.insert(order);

            //6.清空购物车
            cartService.clean();


        }


    }

    //历史订单
    @Override
    public Page<Order> findOrderByPage(Integer pageName, Integer pageSize) {
        //开启分页
        Page<Order> page = new Page<>(pageName, pageSize);
        //构建条件
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.eq(Order::getUserId,UserHolder.get().getId());//根据用户id查找用户订单
        qw.orderByDesc(Order::getOrderTime);//根据下单时间排序

        //调用mapper
        page = orderMapper.selectPage(page,qw);

        //遍历
        for (Order order : page.getRecords()) {
            //构建条件
            LambdaQueryWrapper<OrderDetail> dqw = new LambdaQueryWrapper<>();
            dqw.eq(OrderDetail::getOrderId,order.getId());//根据id查找菜品
            //调用mapper查询
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(dqw);
            //将菜品集合设置给订单
            order.setOrderDetails(orderDetails);
        }


        return page;
    }

    //订单明细
    @Override
    public Page<Order> findByPage(Integer pageName, Integer pageSize,Long number,String beginTime,String endTime) {
        //开启分类
        Page<Order> page = new Page<>(pageName, pageSize);

        //构建条件
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.like(number!=null,Order::getId,number);//根据id查询
        qw.between(StrUtil.isNotBlank(beginTime)&StrUtil.isNotBlank(endTime),Order::getOrderTime,beginTime,endTime);

        //调用mapper
        page = orderMapper.selectPage(page,qw);


        return page;
    }
}
